import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/material.dart';
import 'package:my_shop/cache_event_identification.dart';
import 'package:my_shop/load_my_goods.dart';
import 'package:my_shop/silding_goods_list/silding_good_every_page.dart';

class SlidingGoodListPage extends StatefulWidget {
  const SlidingGoodListPage(this.jumpMyPage, this.showBack, {Key? key})
      : super(key: key);
  final Function jumpMyPage;
  final bool showBack;

  @override
  // ignore: library_private_types_in_public_api
  _SlidingGoodListPageState createState() => _SlidingGoodListPageState();
}

class _SlidingGoodListPageState extends State<SlidingGoodListPage> {
  double viewportFraction = 0.8;

  List<GoodModel> allGoodsList = [];

  PageController pageController = PageController(viewportFraction: 0.9);

  @override
  void initState() {
    super.initState();

    /// Items with zero stock are also displayed
    /// But Items with zero cannot be purchased or added to the cart
    allGoodsList = SpUtil.getObjList<GoodModel>(Constant.allGoodsList,
            (v) => GoodModel.fromJson(v as Map<String, dynamic>)) ??
        [];
  }

  void resetPageController(double param) {
    setState(() {
      pageController = PageController(viewportFraction: param);
    });
  }

  @override
  void dispose() {
    super.dispose();
    pageController.dispose();
  }

  List<Widget> _getPageList() {
    final List<Widget> pageList = [];
    pageList.clear();
    if (allGoodsList.isNotEmpty == true) {
      for (int i = 0; i < allGoodsList.length; i++) {
        pageList.add(SlidingGoodListItemPage(
            allGoodsList[i], i == 0, widget.jumpMyPage));
      }
    }
    return pageList;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: widget.showBack ? AppBar() : null,
        body: Stack(
          children: [
            PageView(
              scrollDirection: Axis.vertical,
              padEnds: false,
              controller: pageController,
              onPageChanged: (int index) {
                if (index > 3) {
                  resetPageController(1);
                } else {
                  resetPageController(0.9);
                }
              },
              children: _getPageList(),
            ),
          ],
        ));
  }
}
